package com.fooddiary.dao.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fooddiary.dao.IWeightDao;
import com.fooddiary.model.Model;
import com.fooddiary.model.Weight;
import com.fooddiary.util.AppConstants;
import com.fooddiary.util.SortPaginationBean;

/**
 * 
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
@Repository
public class WeightDao extends ModelDao implements IWeightDao{
	
	private final String PROPERTY_DATE = "date";
	
	@SuppressWarnings("unchecked")
	public List<Weight> getWeightRecords(Model p_model, SortPaginationBean p_sortPaginationBean){
		DetachedCriteria criteria = DetachedCriteria.forClass(Weight.class)
		.add(Restrictions.eq(PROPERTY_ENABLED, AppConstants.ENTITY_STATE_ENABLED))
		.add(Restrictions.eq(PROPERTY_MODEL, p_model))
		.addOrder( Order.desc( PROPERTY_DATE ) );
		criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );
		return hibernateTemplate.findByCriteria( criteria );
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Weight getEnabledWeightForModelById(Model p_model, Integer p_id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Weight.class)
		.add(Restrictions.eq(PROPERTY_ENABLED, AppConstants.ENTITY_STATE_ENABLED))
		.add(Restrictions.eq(PROPERTY_MODEL, p_model))
		.add(Restrictions.eq(PROPERTY_ID, p_id ));
		List<Weight> records = hibernateTemplate.findByCriteria(criteria);
		return CollectionUtils.isNotEmpty( records ) ? records.get( 0 ) : null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Long getMaxDateOfExistingWeightRecords(Model p_model) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Weight.class)
		.setProjection(Projections.max(PROPERTY_DATE))
		.add(Restrictions.eq(PROPERTY_ENABLED, AppConstants.ENTITY_STATE_ENABLED))
		.add(Restrictions.eq(PROPERTY_MODEL, p_model));
		List<Long> records = hibernateTemplate.findByCriteria(criteria);
		return CollectionUtils.isNotEmpty( records ) ? records.get( 0 ) : null;
	}
	
	/*
	@SuppressWarnings("unchecked")
	@Override
	public Weight getEnabledWeightForModelBetweenDates(Model p_model, Long p_startDate, Long p_endDate) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Weight.class)
		.add(Restrictions.eq(PROPERTY_ENABLED, AppConstants.ENTITY_STATE_ENABLED))
		.add(Restrictions.eq(PROPERTY_MODEL, p_model))
		.add(Restrictions.between(PROPERTY_DATE, p_startDate, p_endDate ));
		List<Weight> records = hibernateTemplate.findByCriteria(criteria);
		return CollectionUtils.isNotEmpty( records ) ? records.get( 0 ) : null;
	}
	*/
	
	
}
